package cn.czh.service.impl;

import cn.czh.domain.Middle;
import cn.czh.domain.Movie;
import cn.czh.domain.User;
import cn.czh.feign.MovieFeignClient;
import cn.czh.mapper.UserMapper;
import cn.czh.service.IUserService;
import cn.czh.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MovieFeignClient movieFeignClient;

    /**
     * 根据id查询用户
     *
     * @param id
     * @return
     */
    @Override
    public User getById(Long id) {
        return userMapper.getById(id);
    }

    /**
     * 购票业务
     *
     * @param middle
     */
    @Override
    @Transactional
    public void buy(Middle middle) {
        //获取电影票信息
        Movie movie = movieFeignClient.getById(middle.getMovie_ticket_id());
        //判断用户是否存在
        User user = userMapper.getById(middle.getUser_id());
        if (user == null) {
            throw new RuntimeException("该用户不存在");
        }
        //判断用户余额是否可以购买电影票
        if (user.getBalance().compareTo(movie.getPrice()) < 0) {
            throw new RuntimeException("抱歉您得余额不足");
        }
        AjaxResult result = movieFeignClient.buy(middle);
        if (!result.getSuccess()) {
            throw new RuntimeException(result.getMsg());
        }
        //买票成功后减余额
        user.setBalance(user.getBalance().subtract(movie.getPrice()));
        //更新数据
        userMapper.update(user);
    }

    /**
     * 新增用户并随机赠送一张电影票
     *
     * @param user
     */
    @Override
    public void addUser(User user) {
        if (user.getUsername() == null) {
            throw new RuntimeException("请填写用户名");
        }
        userMapper.addUser(user); //新增用户

        //随机获取电影票信息,并且赠送电影票的库存不能为空
        Movie movie = movieFeignClient.random();
        //赠送电影票后对应电影库存减一
        movie.setStock(movie.getStock() - 1);
        //修改或新增电影票库存
        movieFeignClient.addOrUpdateMt(movie);
        //新建一个中间表对象
        Middle middle = new Middle();
        //设置user_id
        middle.setUser_id(user.getId());
        //设置值movie_ticket_id
        middle.setMovie_ticket_id(movie.getId());
        //赠送电影票，其实就是买票，只是不会减用户余额
        movieFeignClient.buy(middle);
    }


    @Override
    public void updateUser(User user) {

    }

    /**
     * 观看电影
     *
     * @param middle
     */
    @Override
    public void seeMovie(Middle middle) {
        AjaxResult ajaxResult = movieFeignClient.seeMovie(middle);
        if (!ajaxResult.getSuccess()) { //如果不成功
            throw new RuntimeException(ajaxResult.getMsg());
        }
    }
}
